<template>
  <div class="app-container">
    <el-form>
      <el-form-item label="状态：" prop="status">
        <el-select
          v-model="status"
          clearable
          placeholder="请选择状态"
          @change="selectStatus"
        >
          <el-option
            v-for="(key, val) in statusMap"
            :key="key"
            :label="key"
            :value="val"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <el-table
      :data="list"
      :header-row-style="{
        'background-color': '#E6E6E6',
        'font-weight': 'bold',
        color: '#333'
      }"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      height="650"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
    >
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="innerCode"
        label="内部订单编号"
        width="160px"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="chartNo"
        label="图号"
        width="180px"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="materialName"
        label="物料名称"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="materialType"
        label="物料类型"
      >
        <template slot-scope="scope">
          {{ materialTypeMap[scope.row.materialType] || "--" }}
        </template>
      </el-table-column>

      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="materialType"
        label="采购类型"
      >
        <template slot-scope="scope">
          {{
            scope.row.materialType == 2
              ? purchaseTypeMap[scope.row.purchaseType]
              : "--"
          }}
        </template>
      </el-table-column>

      <!-- <el-table-column
        show-overflow-tooltip
        align="center"
        prop="brand"
        label="品牌"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="specifications"
        label="规格"
      /> -->
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="applyAmount"
        label="申请数量"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="unit"
        label="单位"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="purchaseAmount"
        label="购买数量"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="qualityAmount"
        label="品检合格数"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="unqualityAmount"
        label="品检不合格数"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        width="180"
        prop="arrivalTime"
        label="到货时间"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="supplierName"
        width="200"
        label="供应商名称"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="status"
        width="140"
        label="状态"
      >
        <template slot-scope="scope">
          {{ statusMap[scope.row.status] }}
        </template>
      </el-table-column>
      <!-- <el-table-column show-overflow-tooltip align="center" prop="deliveryTime" label="状态"/>
                <el-table-column show-overflow-tooltip align="center" prop="creator" label="状态" /> -->
      <!-- <el-table-column
        show-overflow-tooltip
        align="center"
        prop="price"
        label="价格"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="totalPrice"
        label="总价格"
      /> -->
      <!-- <el-table-column
        show-overflow-tooltip
        align="center"
        prop="operator"
        label="操作者"
      >
        <template slot-scope="scope">
          {{
            scope.row.operator &&
            scope.row.operator.indexOf("{") > -1 &&
            scope.row.operator.indexOf("}") > -1 &&
            scope.row.operator.indexOf(",") > -1
              ? JSON.parse(scope.row.operator).fullName
              : scope.row.operator
          }}
        </template>
      </el-table-column> -->
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="comment"
        label="备注"
      />
      <el-table-column
        show-overflow-tooltip
        align="center"
        prop="comment"
        label="附件">
        <template slot-scope="scope">
          <a :href="scope.row.url" style="color:#409EFF" v-if="scope.row.url">
           查看
          </a>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 6 && scope.row.purchaseType == 2"
            type="text"
            size="mini"
            @click="inspectionAction(scope.row)"
          >
            品检
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      style="padding: 30px 0; text-align: end"
      layout="total, prev, pager, next,jumper"
      @current-change="fetchData"
    />

    <el-dialog title="品检操作" :visible.sync="inspection.dialogshow">
      <el-form
        ref="form"
        :model="inspection.form"
        :rules="inspection.rules"
        label-width="140px"
      >
        <el-form-item label="物料名称">
          {{ inspection.row.materialName }}
        </el-form-item>

        <el-form-item label="本次采购数量">
          {{ inspection.row.currentPurchaseAmount }}
        </el-form-item>

        <el-form-item label="品检时间" prop="qualityTime">
          <el-date-picker
            v-model="inspection.form.qualityTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择品检时间"
          />
        </el-form-item>

        <el-form-item prop="qualityAmount" label="品检合格数量">
          <el-input-number
            v-model="inspection.form.qualityAmount"
            ref="qualityAmount"
            :min="0"
            :max="inspection.row.currentPurchaseAmount"
            placeholder="请输入品检合格数量"

          />
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item prop="notQualityAmount" label="品检不合格数量">
              <el-input-number
                v-model="inspection.form.unQualityAmount"
                ref="notQualityAmount"
                :min="0"
                :max="inspection.row.currentPurchaseAmount"
                placeholder="品检不合格数量"

              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item prop="notQualityRemark" label="不合格原因">
              <el-input
                type="textarea"
                v-model="inspection.form.unQualityReason"
              ></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-form-item label="备注" prop="comment">
          <el-input
            :rows="2"
            v-model.trim="inspection.form.comment"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>

        <el-form-item label="上传附件">
          <el-button
            type="primary"
            style="text-align: right"
            @click="importFile"
            >导入</el-button
          >
        </el-form-item>
        <el-form-item label="上传文件列表" v-if="inspection.form.url">
          <a  :href="inspection.form.url" style="color:#409EFF" target="_blank">{{inspection.form.url}}</a>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="inspection.loading"
          type="primary"
          @click="confirmInspectionAction"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogFileUpload.show" title="导入" width="400px">
      <el-form>
        <el-form-item label="文件上传：">
          <template v-if="dialogFileUpload.fileName.length == 0">
            <el-upload
              :multiple="false"
              :http-request="httpRequest"
              :before-upload="beforeUploadFile"
              action="#"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </template>

          <div v-else class="the-file">
            {{ dialogFileUpload.fileName }}
            <el-button
              type="danger"
              size="small"
              class="the-file-delete"
              icon="el-icon-delete"
              @click="removeFile"
            />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            :disabled="dialogFileUpload.disabled"
            :loading="dialogFileUpload.loading"
            type="primary"
            @click="confirmUpload"
            >确认上传</el-button
          >
          <el-button @click="closeUploadFileDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import user from "../../api/acl/user.js";
import {
  random,
  parseTime,
  timeFormat,
  isoTimeFormat
} from "../../utils/index";
import { materialTypeMap, purchaseTypeMap } from "../../utils/const";

export default {
  name: "qualityInspection",

  data() {
    var validateQualityAmount = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error("请输入合格数量"));
      } else {
        if (value) {
          if (value > this.inspection.row.currentPurchaseAmount) {
            callback(new Error("输入的合格数量超过了本次的购买数量！"));
          }
        }
        callback();
      }
    };

    var validateNotQualityAmount = (rule, value, cb) => {
      let { form, row } = this.inspection;
      if (form.validateQualityAmount < row.currentPurchaseAmount) {
        // if (value == 0) {
        //   cb(new Error("不合格数量不能为0"));
        // }
      }

      cb();
    };

    var validatequalityTime = (rule, value, cb) => {
      if (!value) {
        cb(new Error("请选择品检时间"));
      }

      cb();
    };

    return {
      materialTypeMap,
      purchaseTypeMap,
      statusMap: {
        0: "待审核",
        1: "申请中",
        2: "采购完成，待到货",
        6: "到货，待品检",
        3: "品检完成",
        4: "品检完成部分",
        5: "入库完成"
      },
      list: [],
      page: 1,
      total: 1,
      limit: 10,
      status: "",
      inspection: {
        dialogshow: false,
        loading: false,
        row: {},
        rules: {
          qualityAmount: [
            {
              validator: validateQualityAmount,
              //required: true,
              message: "请输入合格数量",
              trigger: "blur"
            }
          ],
          notQualityAmount: [
            {
              validator: validateNotQualityAmount,
              //required: true,
              message: "请输入不合格数量",
              trigger: "blur"
            }
          ],
          qualityTime: [
            {
              validator: validatequalityTime,
              required: true,
              trigger: "change"
            }
          ]
        },
        form: {
          qualityAmount: "",
          qualityTime: "",
          unQualityAmount: 0,
          unQualityReason: "",
          unQualityAttachment: "",
          status: "",
          comment: "",
          url:"",
          operator:
            window.sessionStorage.getItem("userName") ||
            window.sessionStorage.getItem("fullName")
        }
      },
      dialogFileUpload: {
        show: false,
        id: "",
        loading: false,
        disabled: false,
        fileName: "",
        code: "",
        formData: null,
        row: {}
      }
    };
  },

  watch: {
    "inspection.row": {
      immediate: true,
      handler(row) {
        this.inspection.form.qualityAmount = row.currentPurchaseAmount;
      }
    }
  },

  created() {
    this.getList();
  },

  methods: {
    // 不合格数量失去焦点
    notQualityAmountBlur(val) {
      this.inspection.form.qualityAmount =
        this.inspection.row.currentPurchaseAmount -
        this.inspection.form.unQualityAmount;
    },
    // 合格数量失去焦点
    qualityAmountBlur() {
      this.inspection.form.unQualityAmount =
        this.inspection.row.currentPurchaseAmount -
        this.inspection.form.qualityAmount;
    },
    selectStatus(val) {
      this.status = val;
      this.getList();
    },
    reset() {
      this.query = {
        brand: "",
        materialName: "",
        specifications: "",
        chartNo: "",
        page: 1,
        limit: 10
      };
      this.getList();
    },
    selected() {
      this.getList();
    },
    fetchData(val) {
      this.page = val;
      this.getList();
    },
    getList() {
      let query = {
        page: this.page,
        limit: this.limit,
        status: this.status
      };

      user.purchaseList(query).then(response => {
        this.total = response.total;
        this.list = (response.list || []).map(item => {
          item.arrivalTime =
            (item.arrivalTime &&
              isoTimeFormat(
                new Date(item.arrivalTime),
                "YYYY-MM-DD HH:mm:ss"
              )) ||
            "--";
          return item;
        });
      });
    },
    inspectionAction(row) {
      this.inspection.row = row;
      this.inspection.dialogshow = true;
    },
    confirmInspectionAction() {
      let { row, form } = this.inspection;
      let data = {
        id: row.id,
        qualityAmount: form.qualityAmount,
        qualityTime: form.qualityTime
          ? form.qualityTime
          : "", //送货日期
        status:
          form.qualityAmount * 1 + row.realAmount * 1 < row.applyAmount ? 4 : 3,
        comment: form.comment,
        operator: form.operator,
        unQualityAmount: form.unQualityAmount,
        unQualityReason: form.unQualityReason,
        url:form.url,
        unQualityAttachment: form.unQualityAttachment
      };

      this.$refs.form.validate(valid => {
        if (valid) {
          this.inspection.loading = true;
          user
            .purchaseApplyUpdate(data)
            .then(res => {
              this.$message.success("操作成功");
              this.$refs.form.resetFields();
              this.inspection.loading = false;
              this.inspection.dialogshow = false;
              this.inspection.form.qualityAmount = 1;
              this.getList();
            })
            .catch(err => {
              this.inspection.loading = false;
            });
        }
      });
    },
    importFile() {
      this.dialogFileUpload.show = true;
      this.dialogFileUpload.disabled = false;
      this.dialogFileUpload.row = {};
    },
    beforeUploadFile(file) {
      const {
        excelType,
        dialogFileUpload: { row }
      } = this;

      const fileName = file.name
        .substring(file.name.lastIndexOf(".") + 1)
        .toLowerCase();

      // 验证excel类型
      //   if (!excelType.includes(fileName)) {
      //     this.$message({
      //       message: `上传文件只能是 ${excelType.join("、")}格式!`,
      //       type: "warning"
      //     });
      //     return false;
      //   }

      const formData = new FormData();
      formData.append("file", file);

      this.dialogFileUpload.fileName = file.name;
      this.dialogFileUpload.formData = formData;
    },
    closeUploadFileDialog() {
      this.dialogFileUpload.fileName = "";
      this.dialogFileUpload.formData = null;
      this.dialogFileUpload.show = false;
    },
    removeFile() {
      this.dialogFileUpload.fileName = "";
      this.dialogFileUpload.formData = null;
    },
    httpRequest() {},
    confirmUpload() {
      const {
        dialogFileUpload: { row, fileName, formData }
      } = this;

      if (!fileName || !formData) return false;

      this.dialogFileUpload.loading = true;

      //   console.log("this.formData: ", formData);
      user.objectLinkPdf(formData).then(response => {
        this.inspection.form.unQualityAttachment = response;
        this.inspection.form.url = response
        this.dialogFileUpload.loading = false;
        this.dialogFileUpload.disabled = true;
        debugger
        this.$message.success("导入成功");

        this.closeUploadFileDialog();
      });
    }
  }
};
</script>

<style>
.establish {
  text-align: right;
}

.s-input {
  min-width: 220px;
}
</style>
